package com.guchenbo.example.socket.bio;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.KeyStore;

/**
 * @Author gucb
 * @Date 15/09/2017.
 */
public class HttpsClient {

    public static void main(String[] args) {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            String key = System.getProperty("java.home") + "/lib/security/cacerts";
            keyStore.load(new FileInputStream(key), null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, null);

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("SSLv3");
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            Socket socket = socketFactory.createSocket("127.0.0.1", 8889);

            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            byte[] b = new byte[1024];
            inputStream.read(b);

            String s = new String(b);
            System.out.println(s);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
